const {isEmpty} = require("lodash");

function array2Tree(array,idKey){
    let returnList = [];
    let pidList = array.map(m=>m[idKey]);
    array.forEach(m=>{
        if (pidList.includes(m[idKey])){
            recursionFn(array,m)
            returnList.push(m)
        }
    })
    if (isEmpty(returnList)){
        returnList = array
    }
    return returnList;
}
function recursionFn(list,m){
    let childList = getChildList(list,m);
    m.children = childList;
    for (const item of childList) {
        if (hasChild(list,item)){
            recursionFn(list,item)
        }
    }

}
function getChildList(list,m){
    const result = [];
    for (const item of list) {
        if (item.menuId === m.menuId){
            result.push(item)
        }
    }
    return result;
}

function hasChild(list,m){
    return 'children' in m && !isEmpty(m.children);
}

function arrToTree(arr, parentId) {
    return arr.filter(item => parentId === undefined ? item.parentId === 0 : item.parentId === parentId ).map( item => {
        item.children = arrToTree(arr, item.menuId)
        return item
    })
}

module.exports = {array2Tree,arrToTree}
